import 'package:flutter/material.dart';
import 'package:flutter_bsbdj/pagers/episodes/episode_comment.dart';
import 'package:flutter_bsbdj/utils/constant.dart';
import 'package:flutter_bsbdj/utils/http_util.dart';
import 'package:flutter_bsbdj/bean/hot_episode.dart';
import 'package:dio/dio.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
import 'package:flutter_bsbdj/bean/god_episode.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_bsbdj/dialogs/big_image_dialog.dart';

//段子
class EpisodePager extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return EpisodeWidget();
  }
}

class EpisodeWidget extends State<EpisodePager> {
  int type = 0;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Container(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              GestureDetector(
                child: Container(
                  child: Text("热门段子", style: _setStyleByType(0)),
                ),
                onTap: () {
                  setState(() {
                    type = 0;
                  });
                },
              ),
              GestureDetector(
                child: Container(
                  margin: EdgeInsets.only(left: 10),
                  child: Text(
                    "神评版",
                    style: _setStyleByType(1),
                  ),
                ),
                onTap: () {
                  setState(() {
                    type = 1;
                  });
                },
              )
            ],
          ),
        ),
        actions: <Widget>[
          Container(
            width: 50,
          )
        ],
        elevation: 0,
      ),
      body: IndexedStack(
        children: <Widget>[
          Hot(),
          GodComment(),
        ],
        index: type,
      ),
    );
  }

  TextStyle _setStyleByType(int stand) {
    if (type == stand) {
      return TextStyle(fontWeight: FontWeight.bold, color: Colors.white);
    } else {
      return TextStyle(fontWeight: FontWeight.normal, color: Colors.grey);
    }
  }
}

//热门段子
class Hot extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return HotWidget();
  }
}

class HotWidget extends State<Hot> {
  ScrollController _controller = ScrollController();
  List<Episode> _episodes;
  int page = 1;
  String playId = "0";
  VideoPlayerController _videoPlayerController;
  ChewieController _chewieController;
  bool loading = true;
  bool loadError = false;

  Constant _constant;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller.addListener(() {
      var pix = _controller.position.pixels;
      var max = _controller.position.maxScrollExtent;
      if (pix == max) {
        page++;
        _getHotEpisode();
      }

      if (_videoPlayerController != null) {
        if (_videoPlayerController.value.isPlaying) {
          _videoPlayerController.pause();
        }
      }
    });
    _getHotEpisode();
    _constant=Constant.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return loading
        ? (loadError
            ? Container(
                child: GestureDetector(
                  child: Text("加载失败！点击刷新"),
                  onTap: () {
                    _getHotEpisode();
                    setState(() {
                      loadError = false;
                    });
                  },
                ),
              )
            : Container(
                alignment: Alignment.center,
                child: Container(
                  width: 30,
                  height: 30,
                  margin: EdgeInsets.all(5),
                  child: CircularProgressIndicator(),
                ),
              ))
        : ListView.builder(
            itemCount: _episodes == null ? 0 : _episodes.length + 1,
            itemBuilder: (content, index) {
              if (index == _episodes.length) {
                return Container(
                  child: Container(
                    width: 30,
                    height: 30,
                    margin: EdgeInsets.all(10),
                    child: CircularProgressIndicator(),
                  ),
                  alignment: Alignment.center,
                );
              } else {
                Episode item = _episodes[index];
                return Container(
                  margin: EdgeInsets.all(5),
                  padding: EdgeInsets.all(8),
                  color: _constant.getItemColor(),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          Container(
                            width: 30,
                            height: 30,
                            margin: EdgeInsets.all(5),
                            child: ClipOval(
                              child: Image.network(item.profile_image),
                            ),
                          ),
                          Expanded(
                            child: Text(item.name),
                          ),
                          Text(
                            item.created_at,
                            style: TextStyle(color: Colors.grey, fontSize: 12),
                          )
                        ],
                      ),
                      _contentByType(item),
                      Container(
                        height: 40,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            _bottomOptionItem(Icons.thumb_up, item.love),
                            _bottomOptionItem(Icons.thumb_down, item.hate),
                            _bottomOptionItem(Icons.comment, item.comment),
                            _bottomOptionItem(Icons.bookmark, item.bookmark),
                          ],
                        ),
                      )
                    ],
                  ),
                );
              }
            },
            controller: _controller,
          );
  }

  Widget _contentByType(Episode item) {
    if (item.videouri != null && item.videouri.isNotEmpty) {
      var width = MediaQuery.of(context).size.width - 30;
      var height = width * double.parse(item.height) / double.parse(item.width);
      if (height > MediaQuery.of(context).size.height - 100) {
        width = (MediaQuery.of(context).size.height - 100) * width / height;
        height = MediaQuery.of(context).size.height - 100;
      }
      if (playId == item.videouri) {
        _videoPlayerController = VideoPlayerController.network(item.videouri);
        _chewieController = ChewieController(
            videoPlayerController: _videoPlayerController,
            autoPlay: true,
            aspectRatio: width / height);
        return Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(top: 5, bottom: 8),
                child: Text(item.text),
              ),
              Container(
                alignment: Alignment.center,
                child: Container(
                  width: width,
                  height: height,
                  child: Chewie(
                    controller: _chewieController,
                  ),
                ),
              )
            ],
          ),
        );
      } else {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(top: 5, bottom: 8),
              child: Text(item.text),
            ),
            Stack(
              children: <Widget>[
                Container(
                  child: Container(
                    child: _cachedImage(item.bimageuri),
                    width: width,
                    height: height,
                  ),
                  alignment: Alignment.center,
                ),
                IconButton(
                  icon: Icon(
                    Icons.play_circle_filled,
                    color: Colors.white,
                    size: 40,
                  ),
                  onPressed: () {
                    setState(() {
                      playId = item.videouri;
                    });
                  },
                ),
              ],
              alignment: Alignment.center,
            )
          ],
        );
      }
    } else if (item.bimageuri != null && item.bimageuri.isNotEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(top: 5, bottom: 8),
            child: Text(item.text),
          ),
          Container(
            alignment: Alignment.center,
            child: _cachedImage(item.bimageuri),
          )
        ],
      );
    } else if (item.cdn_img != null && item.cdn_img.isNotEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(top: 5, bottom: 8),
            child: Text(item.text),
          ),
          Container(
            alignment: Alignment.center,
            child: _cachedImage(item.cdn_img),
          )
        ],
      );
    } else {
      return Container(
        child: Container(
          margin: EdgeInsets.only(top: 5, bottom: 8),
          child: Text(item.text),
        ),
      );
    }
  }

  Widget _bottomOptionItem(IconData icon, String value) {
    return Expanded(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Icon(
            icon,
            color: Colors.grey,
            size: 14,
          ),
          Container(
            margin: EdgeInsets.only(left: 5),
            child: Text(
              value,
              style: TextStyle(color: Colors.grey),
            ),
          )
        ],
      ),
    );
  }

  //返回带错误提示的image
  Widget _cachedImage(String url) {
    return GestureDetector(
      child: CachedNetworkImage(
        imageUrl: url,
        placeholder: (context, str) => Image.asset("images/ic_loading.gif"),
        errorWidget: (context, str, object) => Image.asset("images/error.png"),
      ),
      onTap: () {
//        showDialog(context: context,builder: (BuildContext context){
//          return ShowBigImage(url,false);
//        });
        Navigator.of(context).push(
            MaterialPageRoute(builder: (context) => ShowBigImage(url, false)));
      },
    );
  }

  void _getHotEpisode() async {
    FormData formData = FormData();
    formData.add("type", 1);
    formData.add("page", page);
    var res = await HttpUtil().post("satinApi", data: formData).then((result) {
      try {
        HotEpisode hotEpisode = HotEpisode.fromJson(result.data);
        print(hotEpisode);
        var data = _episodes;
        if (data == null) {
          data = hotEpisode.data;
        } else {
          data.addAll(hotEpisode.data);
        }
        //只有当前widget还在 tree中才设置值
        if (mounted) {
          setState(() {
            loading = false;
            loadError = false;
            _episodes = data;
          });
        }
      } catch (e) {
        if (mounted) {
          setState(() {
            loading = true;
            loadError = true;
          });
        }
      }
    });
  }
}

//神评版
class GodComment extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return GodWidget();
  }
}

class GodWidget extends State<GodComment> {
  ScrollController _controller = ScrollController();
  List<Godsode> _episodes;
  int page = 1;
  int type = 1;
  String playId = "0";
  VideoPlayerController _videoPlayerController;
  ChewieController _chewieController;
  bool loading = true;
  bool loadError = false;

  Constant _constant;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller.addListener(() {
      var pix = _controller.position.pixels;
      var max = _controller.position.maxScrollExtent;
      if (pix == max) {
        page++;
        _getHotEpisode();
      }

      if (_videoPlayerController != null) {
        if (_videoPlayerController.value.isPlaying) {
          _videoPlayerController.pause();
        }
      }
    });
    _getHotEpisode();
    _constant=Constant.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            height: 1,
            color: Colors.grey,
          ),
          Container(
            height: 50,
            width: MediaQuery.of(context).size.width,
            child: Row(
              children: <Widget>[
                _godType("全部", 1),
                _godType("文字", 2),
                _godType("图片", 3),
                _godType("GIF", 4),
                _godType("视频", 5)
              ],
            ),
          ),
          loading
              ? (loadError
                  ? Container(
                      child: GestureDetector(
                        child: Text("加载失败！点击刷新"),
                        onTap: () {
                          _getHotEpisode();
                          setState(() {
                            loadError = false;
                          });
                        },
                      ),
                    )
                  : Container(
                      alignment: Alignment.center,
                      child: Container(
                        width: 30,
                        height: 30,
                        margin: EdgeInsets.all(5),
                        child: CircularProgressIndicator(),
                      ),
                    ))
              : Expanded(
                  child: ListView.builder(
                    itemCount: _episodes == null ? 0 : _episodes.length + 1,
                    itemBuilder: (content, index) {
                      if (index == _episodes.length) {
                        return Container(
                          child: Container(
                            width: 30,
                            height: 30,
                            margin: EdgeInsets.all(10),
                            child: CircularProgressIndicator(),
                          ),
                          alignment: Alignment.center,
                        );
                      } else {
                        Godsode item = _episodes[index];
                        return Container(
                          margin: EdgeInsets.all(5),
                          padding: EdgeInsets.all(8),
                          color: _constant.getItemColor(),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Row(
                                children: <Widget>[
                                  Container(
                                    width: 30,
                                    height: 30,
                                    margin: EdgeInsets.all(5),
                                    child: ClipOval(
                                      child: Image.network(item.header),
                                    ),
                                  ),
                                  Expanded(
                                    child: Text(item.username),
                                  ),
                                  Text(
                                    item.passtime,
                                    style: TextStyle(
                                        color: Colors.grey, fontSize: 12),
                                  )
                                ],
                              ),
                              _contentByType(item),
                              Container(
                                height: 40,
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    _bottomOptionItem(
                                        Icons.thumb_up, "${item.up}", null),
                                    _bottomOptionItem(
                                        Icons.thumb_down, "${item.down}", null),
                                    _bottomOptionItem(
                                        Icons.comment, "${item.comment}", () {
                                      Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  EpisodeComment(
                                                      item.soureid)));
                                    }),
                                    _bottomOptionItem(
                                        Icons.forward, "${item.forward}", null),
                                  ],
                                ),
                              )
                            ],
                          ),
                        );
                      }
                    },
                    controller: _controller,
                  ),
                )
        ],
      ),
    );
  }

  Widget _godType(String name, int t) {
    return Expanded(
      child: GestureDetector(
        child: Center(
          child: Text(
            name,
            style: TextStyle(
                color: type == t ? Colors.white70 : Colors.grey,
                fontWeight: type == t ? FontWeight.bold : FontWeight.normal,
                fontSize: type == t ? 16 : 14),
          ),
        ),
        onTap: () {
          if (type != t) {
            setState(() {
              type = t;
              page = 1;
              loading = true;
              _getHotEpisode();
            });
          }
        },
      ),
    );
  }

  Widget _contentByType(Godsode item) {
    if (item.type == "video") {
      if (playId == item.video) {
        _videoPlayerController = VideoPlayerController.network(item.video);
        _chewieController = ChewieController(
          videoPlayerController: _videoPlayerController,
          autoPlay: true,
        );
        return Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(top: 5, bottom: 8),
                child: Text(item.text),
              ),
              Container(
                alignment: Alignment.center,
                child: Container(
                  child: Chewie(
                    controller: _chewieController,
                  ),
                ),
              )
            ],
          ),
        );
      } else {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(top: 5, bottom: 8),
              child: Text(item.text),
            ),
            Stack(
              children: <Widget>[
                Container(
                  child: Container(
                    child: Image.network(item.thumbnail),
                  ),
                  alignment: Alignment.center,
                ),
                IconButton(
                  icon: Icon(
                    Icons.play_circle_filled,
                    color: Colors.white,
                    size: 40,
                  ),
                  onPressed: () {
                    setState(() {
                      playId = item.video;
                    });
                  },
                ),
              ],
              alignment: Alignment.center,
            )
          ],
        );
      }
    } else if (item.type == "image") {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(top: 5, bottom: 8),
            child: Text(item.text),
          ),
          Container(
            alignment: Alignment.center,
            child: _cachedImage(item.image),
          )
        ],
      );
    } else if (item.type == "gif") {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(top: 5, bottom: 8),
            child: Text(item.text),
          ),
          Container(
            alignment: Alignment.center,
            child: _cachedImage(item.gif),
          )
        ],
      );
    } else {
      return Container(
        child: Container(
          margin: EdgeInsets.only(top: 5, bottom: 8),
          child: Text(item.text),
        ),
      );
    }
  }

  //返回带错误提示的image
  Widget _cachedImage(String url) {
    return GestureDetector(
      child: CachedNetworkImage(
        imageUrl: url,
        placeholder: (context, str) => Image.asset("images/ic_loading.gif"),
        errorWidget: (context, str, object) => Image.asset("images/error.png"),
      ),
      onTap: () {
//        showDialog(context: context,builder: (BuildContext context){
//          return BigImageDialog(url);
//        });
        Navigator.of(context).push(
            MaterialPageRoute(builder: (context) => ShowBigImage(url, false)));
      },
    );
  }

  Widget _bottomOptionItem(IconData icon, String value, Function function) {
    return Expanded(
      child: GestureDetector(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Icon(
              icon,
              color: Colors.grey,
              size: 14,
            ),
            Container(
              margin: EdgeInsets.only(left: 5),
              child: Text(
                value,
                style: TextStyle(color: Colors.grey),
              ),
            )
          ],
        ),
        onTap: function,
      ),
    );
  }

  void _getHotEpisode() async {
    FormData formData = FormData();
    formData.add("type", type);
    formData.add("page", page);
    var res =
        await HttpUtil().post("satinGodApi", data: formData).then((result) {
      try {
        GodEpisode hotEpisode = GodEpisode.fromJson(result.data);
        print(hotEpisode);
        var data = _episodes;
        if (data == null || page == 1) {
          data = hotEpisode.data;
        } else {
          data.addAll(hotEpisode.data);
        }
        //只有当前widget还在 tree中才设置值
        if (mounted) {
          setState(() {
            loading = false;
            _episodes = data;
            loadError = false;
          });
        }
      } catch (e) {
        if (mounted) {
          setState(() {
            loading = true;
            loadError = true;
          });
        }
      }
    });
  }
}
